//
//  MakeFormViewController.swift
//  iModern
//
//  Created by 立雄 王 on 15/7/29.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit
import XLForm

class MakeAppointmentFormViewController: FormViewController
{

    var advertising        = NSDictionary()
    var appointmentManager = AppointmentManager()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.navigationItem.title = "下单"
        self.initBackButton()

        //        let image  = UIImage(named: "Save-Small.png")
        //        let button = UIBarButtonItem(image: image?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "makeAppointmentButtonOnTap:")
        //        self.navigationItem.rightBarButtonItem = button

        self.initializeForm()
    }

    func initializeForm()
    {
        var form:    XLFormDescriptor
        var section: XLFormSectionDescriptor
        var row:     XLFormRowDescriptor

        let article         = advertising["article"] as! NSDictionary
        let contact         = article["contact"] as! [String:AnyObject]
        let indexOfSaleTags = article["indexOfSaleTags"] as? String

        form = XLFormDescriptor(title: "Make Appointment")

        section = XLFormSectionDescriptor.formSectionWithTitle("收货信息")
        form.addFormSection(section)

        row = XLFormRowDescriptor(tag: "address", rowType: XLFormRowDescriptorTypeTextView, title: "收货地址：")
        row.cellConfigAtConfigure["textView.placeholder"] = "请填写您的详细地址"
//        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "nameOfConsignee", rowType: XLFormRowDescriptorTypeText, title: "收货人：    ")
        row.cellConfigAtConfigure["textField.placeholder"] = "收货人姓名"
        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "cellphoneOfConsignee", rowType: XLFormRowDescriptorTypeNumber, title: "手机号码：")
        row.cellConfigAtConfigure["textField.placeholder"] = "收货人手机号码"
        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        section.addFormRow(row)

        section = XLFormSectionDescriptor.formSection()
        form.addFormSection(section)

        //        let shopName = contact["shopName"] as! String
        row = XLFormRowDescriptor(tag: "d", rowType: XLFormRowDescriptorTypeText, title: "店铺名:")
        row.disabled = NSNumber(bool: true)
        row.value = contact["shopName"] as? String
        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "quantity", rowType: XLFormRowDescriptorTypeStepCounter, title: indexOfSaleTags)
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "price", rowType: XLFormRowDescriptorTypeText, title: "价格：")
        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        row.disabled = NSNumber(bool: true)
        row.value = article["price"] as? Int
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "totalPrice", rowType: XLFormRowDescriptorTypeText, title: "共计_个宝贝")
        row.cellConfigAtConfigure["textField.textAlignment"] = NSTextAlignment.Right.rawValue
        row.disabled = NSNumber(bool: true)
        section.addFormRow(row)

        section = XLFormSectionDescriptor.formSectionWithTitle("如有特殊要求可填写:")
        form.addFormSection(section)

        row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeTextView, title: "")
        //        row.cellConfigAtConfigure["textView.placeholder"] = "50字"
        row.cellConfig["textView.font"] = UIFont.systemFontOfSize(15)
        section.addFormRow(row)

        row = XLFormRowDescriptor(tag: "h", rowType: XLFormRowDescriptorTypeButton, title: "总计:￥_元  提交订单")
        row.cellConfigAtConfigure["backgroundColor"] = Theme.theme_color
        row.cellConfig["textLabel.color"] = UIColor.whiteColor()
        row.cellConfig["textLabel.font"] = UIFont.systemFontOfSize(20)
        row.action.formSelector = "didTouchButton:"
        section.addFormRow(row)

        self.form = form
    }

    override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!)
    {
        super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)

        if formRow.tag == "quantity"
        {
            let totalPriceDescriptor                = self.form.formRowWithTag("totalPrice")
            //let totalPriceCell = self.form.formRowWithTag("totalPrice")!.cellForFormController(self) as! XLFormTextFieldCell

            let buttonDescriptor             = self.form.formRowWithTag("h")
            //let buttonCell: XLFormButtonCell = self.form.formRowWithTag("h")!.cellForFormController(self) as! XLFormButtonCell
            let quantity                     = self.formValues()["quantity"] as? Int
            if quantity != nil
            {
                let nub   = formRow.value as? Int
                let price = self.formValues()["price"] as? Int

                totalPriceDescriptor!.value = "合计 ￥\(nub! * price!)"
                totalPriceDescriptor?.title = "共计\( nub! * 1)个宝贝"
                buttonDescriptor?.title = "总计:￥\( nub! * price!)元  提交订单"

            }

            self.updateFormRow(totalPriceDescriptor)
            self.updateFormRow(buttonDescriptor)
        }
    }

    func didTouchButton(sender: XLFormRowDescriptor)
    {
        let data         = advertising["article"] as! NSDictionary
        let contact      = data["contact"] as! NSDictionary
        let appointments = NSMutableDictionary()

        let address = self.formValues()["address"] as? String
        if address == nil
        {
            self.alertWarningMessage("请填写地址")
            self.deselectFormRow(sender)
            return
        }

        let userName = self.formValues()["nameOfConsignee"] as? String
        if userName == nil
        {
//            var data         = advertising["article"] as! NSDictionary
//            let contact      = data["contact"] as! NSDictionary
//            var appointments = NSMutableDictionary()
            self.alertWarningMessage("请填写收货人")
            self.deselectFormRow(sender)
            return
        }

        let phone = self.formValues()["cellphoneOfConsignee"] as? Int
        if phone == nil
        {
            self.alertWarningMessage("请填写手机号码")
            self.deselectFormRow(sender)
            return
        }

        let indexOfSaleTags = self.formValues()["quantity"] as? Int
        if indexOfSaleTags == nil || indexOfSaleTags == 0
        {
            self.alertWarningMessage("请填写商品个数")
            self.deselectFormRow(sender)
            return
        }

        let message = self.formValues()["message"] as? String
        
        let filter = SensitiveWordsFilter()
        let valid: Bool = filter.validating(message)
        if !valid
        {
            self.alertWarningMessage("你在描述里填写的信息可能包含敏感内容.")
            return
        }
        if message == nil
        {
            appointments["message"] = "无"
        }
        else
        {
            appointments["message"] = self.formValues()["message"]
        }

        appointments["userName"] = contact["userName"]
        appointments["advertisingId"] = data["id"];
        appointments["nameOfConsignee"] = self.formValues()["nameOfConsignee"]
        appointments["cellphoneOfConsignee"] = self.formValues()["cellphoneOfConsignee"]
        appointments["quantity"] = self.formValues()["quantity"]
        appointments["address"] = self.formValues()["address"]
        appointments["price"] = self.formValues()["price"]

        let rs = appointmentManager.createAppointment(appointments as [NSObject:AnyObject])

        if rs == nil 
        {
            self.alertNetworkConnectionException()
            return
        }

        if rs!.hasErrors()
        {
            if rs?.errorCode == 3020
            {
                self.alertUserStatusException()
            }
            else
            {
                self.alertErrorMessage(rs!.errorMessage)
            }
        }
        else
        {
            let controller = MyOrderViewController()
            self.pushViewController(controller)
        }

        self.deselectFormRow(sender)
        return
    }

    @IBAction func loadMessageViewController(sender: UIButton)
    {
        let data                 = advertising["article"] as! NSDictionary
        let contacts: AnyObject? = data["contact"]
        if (appDelegate.isLogged())
        {
            let controller = ChatViewController()
            controller.contact = contacts as! [String:AnyObject]
            self.pushViewController(controller)
        }
        else
        {
            self.login()
        }
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}
